<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
<!--       <el-form-item label="材质id" prop="materialId">-->
<!--        <el-input v-model="formData.materialId" placeholder="请输入材质id" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="材质名称" prop="materialName">-->
<!--        <el-input v-model="formData.materialName" placeholder="请输入材质名称" />-->
<!--      </el-form-item>-->
      <el-form-item label="材质名称" prop="materialId">
        <el-select v-model="formData.materialId" placeholder="请选择材质" clearable @change="handleMaterialChange">
          <el-option
            v-for="item in materialList"
            :key="item.id"
            :label="item.materialName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="序号" prop="serialNumber">-->
<!--        <el-input v-model="formData.serialNumber" placeholder="请输入序号" />-->
<!--      </el-form-item>-->
      <el-form-item label="单价" prop="unitPrice">
        <el-input v-model="formData.unitPrice" placeholder="请输入单价" />
      </el-form-item>
      <el-form-item label="旧价" prop="oldPrice">
        <el-input v-model="formData.oldPrice" placeholder="请输入旧价" />
      </el-form-item>
      <el-form-item label="类型" prop="materialType">
        <el-input v-model="formData.materialType" placeholder="请输入类型"/>
      </el-form-item>
<!--      <el-form-item label="代用材质id" prop="substituteMaterialId">-->
<!--        <el-input v-model="formData.substituteMaterialId" placeholder="请输入代用材质id" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="代用材质名称" prop="substituteMaterialName">-->
<!--        <el-input v-model="formData.substituteMaterialName" placeholder="请输入代用材质名称" />-->
<!--      </el-form-item>-->

      <el-form-item label="代用材质名称" prop="substituteMaterialId">
        <el-select v-model="formData.substituteMaterialId" placeholder="请选择材质" clearable @change="handleSubstituteMaterialChange">
          <el-option
            v-for="item in materialList"
            :key="item.id"
            :label="item.materialName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="摘要" prop="summary">
        <el-input v-model="formData.summary" placeholder="请输入摘要" />
      </el-form-item>
      <el-form-item label="克重" prop="density">
        <el-input v-model="formData.density" placeholder="请输入克重" />
      </el-form-item>
      <el-form-item label="楞型" prop="fluteType">
        <el-input v-model="formData.fluteType" placeholder="请输入楞型" />
      </el-form-item>
      <el-form-item label="客户材质名称" prop="customerMaterialName">
        <el-input v-model="formData.customerMaterialName" placeholder="请输入客户材质名称" />
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input v-model="formData.costPrice" placeholder="请输入成本价" />
      </el-form-item>
      <el-form-item label="计价方案" prop="pricingPlan">
        <el-input v-model="formData.pricingPlan" placeholder="请输入计价方案" />
      </el-form-item>
      <el-form-item label="含税价" prop="taxInclusivePrice">
        <el-input v-model="formData.taxInclusivePrice" placeholder="请输入含税价" />
      </el-form-item>
      <el-form-item label="税率" prop="taxRate">
        <el-input v-model="formData.taxRate" placeholder="请输入税率" />
      </el-form-item>
      <el-form-item label="最小厚度" prop="minThickness">
        <el-input v-model="formData.minThickness" placeholder="请输入最小厚度" />
      </el-form-item>
      <el-form-item label="最大厚度" prop="maxThickness">
        <el-input v-model="formData.maxThickness" placeholder="请输入最大厚度" />
      </el-form-item>
      <el-form-item label="最小克重" prop="minDensity">
        <el-input v-model="formData.minDensity" placeholder="请输入最小克重" />
      </el-form-item>
      <el-form-item label="最大克重" prop="maxDensity">
        <el-input v-model="formData.maxDensity" placeholder="请输入最大克重" />
      </el-form-item>
      <el-form-item label="差价" prop="priceDifference">
        <el-input v-model="formData.priceDifference" placeholder="请输入差价" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SaleCustomerQuotationApi } from '@/api/erp/salecustomerquotation'
import {BaseBoxInnerOuterConfigApi} from "@/api/erp/baseboxinnerouterconfig";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  quotationId: undefined,
  materialId: undefined,
  materialName: undefined,
  serialNumber: undefined,
  unitPrice: undefined,
  oldPrice: undefined,
  materialType: undefined,
  substituteMaterialId: undefined,
  substituteMaterialName: undefined,
  summary: undefined,
  density: undefined,
  fluteType: undefined,
  customerMaterialName: undefined,
  costPrice: undefined,
  pricingPlan: undefined,
  taxInclusivePrice: undefined,
  taxRate: undefined,
  minThickness: undefined,
  maxThickness: undefined,
  minDensity: undefined,
  maxDensity: undefined,
  priceDifference: undefined
})
const formRules = reactive({
  quotationId: [{ required: true, message: '主表ID不能为空', trigger: 'blur' }],
  materialId: [{ required: true, message: '材质id不能为空', trigger: 'blur' }],
  materialName: [{ required: true, message: '材质名称不能为空', trigger: 'blur' }],
  serialNumber: [{ required: true, message: '序号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, quotationId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.quotationId = quotationId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SaleCustomerQuotationApi.getSaleCustomerQuotationMaterial(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await SaleCustomerQuotationApi.createSaleCustomerQuotationMaterial(data)
      message.success(t('common.createSuccess'))
    } else {
      await SaleCustomerQuotationApi.updateSaleCustomerQuotationMaterial(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    quotationId: undefined,
    materialId: undefined,
    materialName: undefined,
    serialNumber: undefined,
    unitPrice: undefined,
    oldPrice: undefined,
    materialType: undefined,
    substituteMaterialId: undefined,
    substituteMaterialName: undefined,
    summary: undefined,
    density: undefined,
    fluteType: undefined,
    customerMaterialName: undefined,
    costPrice: undefined,
    pricingPlan: undefined,
    taxInclusivePrice: undefined,
    taxRate: undefined,
    minThickness: undefined,
    maxThickness: undefined,
    minDensity: undefined,
    maxDensity: undefined,
    priceDifference: undefined
  }
  formRef.value?.resetFields()
}


// ** 客户 & 材质列表 ** 
const customerList = ref<{ id: string; name: string }[]>([])
const materialList = ref<{ id: string; materialName: string }[]>([])
const boxTypeList = ref<{ id: string; productTypeName: string }[]>([])

/** 获取客户列表 */
const getAllBaseCustomer = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseCustomer();
    if (response) {
      customerList.value = response;
    }
  } catch (error) {
    console.error("获取客户列表失败:", error);
  }
};
/** 获取箱型 */
const getAllBoxType = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseBoxType();
    if (response) {
      boxTypeList.value = response;
    }
  } catch (error) {
    console.error("获取箱型列表失败:", error);
  }
};

/** 获取材质列表 */
const getAllBaseMaterial = async () => {
  try {
    const response = await BaseBoxInnerOuterConfigApi.getAllBaseMaterial();
    if (response) {
      materialList.value = response;
    }
  } catch (error) {
    console.error("获取材质列表失败:", error);
  }
};

/** 选择客户时，自动填充客户名称 */
const handleCustomerChange = (id: string) => {
  const selectedCustomer = customerList.value.find(item => item.id === id);
  formData.value.customerName = selectedCustomer ? selectedCustomer.name : "";
};

/** 选择客户时，自动填充客户名称 */
const handleBoxTypeChange = (id: string) => {
  const selectedBoxType = boxTypeList.value.find(item => item.id === id);
  formData.value.boxTypeName = selectedBoxType ? selectedBoxType.productTypeName : "";
};

/** 选择材质时，自动填充材质名称 */
const handleMaterialChange = (id: string) => {
  const selectedMaterial = materialList.value.find(item => item.id === id);
  formData.value.materialName = selectedMaterial ? selectedMaterial.materialName : "";
  formData.value.materialId = selectedMaterial ? selectedMaterial.id : "";
};

const handleSubstituteMaterialChange = (id: string) => {
  const selectedMaterial = materialList.value.find(item => item.id === id);
  formData.value.substituteMaterialName = selectedMaterial ? selectedMaterial.materialName : "";
  formData.value.substituteMaterialId = selectedMaterial ? selectedMaterial.id : "";
};

onMounted(() => {
  Promise.all([
    getAllBaseCustomer(), // 获取所有客户
    getAllBaseMaterial(),  // 获取所有材质
    getAllBoxType() // 获取所有箱型
  ])
})
</script>
